<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    showFooter
    @ok="handleSubmit"
    width="60%"
  >
    <BasicForm @register="registerForm">
      <template #roleSlot="{ model, field }">
        <ApiSelect
          :api="getAllRoleList"
          mode="multiple"
          v-model:value="model[field]"
          labelField="roleName"
          valueField="id"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, ApiSelect, useForm } from '/@/components/Form';
  import { formSchema } from './user.data';
  import { getDetail, saveOrUpdateUser } from './user.api';
  import { getDeptList, getAllRoleList } from '/@/api/system/system';

  export default defineComponent({
    name: 'UserDrawer',
    components: { BasicDrawer, BasicForm, ApiSelect },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        baseColProps: { lg: 12, md: 24 },
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          const res = await getDetail(rowId.value);
          setFieldsValue({
            ...res,
          });
        }

        const treeData = await getDeptList();
        updateSchema([
          {
            field: 'password',
            show: !unref(isUpdate),
          },
          {
            field: 'deptId',
            componentProps: { treeData },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          await saveOrUpdateUser(values, isUpdate.value);
          closeDrawer();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit, getAllRoleList };
    },
  });
</script>
